package com.asset.dispoal.file.clouddesk.service.command;

import com.asset.dispoal.file.clouddesk.dto.CloudDeskAddRequest;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.file.FileUtil;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.io.File;

@Component
@Slf4j
public class CloudDeskCreateCommand implements BaseCommand<CloudDeskAddRequest, Result> {
    @Autowired
    private Environment environment;

    @SneakyThrows
    @Override
    public Result execute(CloudDeskAddRequest request) {
        String headUrl = environment.getProperty("file.evidence.url");
        String cloudDeskFolder = environment.getProperty("file.cloudDesk.url");
        StringBuilder strBuilder = new StringBuilder();
        strBuilder.append(headUrl)
                .append(File.separator)
                .append(cloudDeskFolder)
                .append(File.separator)
                .append(request.getAssetInstBatchId())
                .append(File.separator);
        if (StringUtil.isNotEmpty(request.getDirName())) {
            strBuilder.append(request.getDirName()).append(File.separator);
        }
        File checkDirFile = new File(strBuilder.toString());
        if (!checkDirFile.exists()) {
            FileUtil.createDirectory(checkDirFile, true);
        }
        if (request.getFile() != null) {
            request.getFile().transferTo(new File(strBuilder + request.getFile().getOriginalFilename()));
        }
        return Result.ok();
    }
}
